package njupt.Servlet;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.util.mail.MailSenderInfo;
import com.util.mail.SimpleMailSender;

import njupt.vo.Cart;
import njupt.vo.Goods;
import factory.DAOFactory;

public class GoodsServlet extends HttpServlet {





	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		  req.setCharacterEncoding("GB2312");
		 // List cartinfo=new ArrayList();
		  resp.setCharacterEncoding("GB2312");
		  HttpSession session=req.getSession(true);
		  Goods goods = (Goods)session.getAttribute("goods");
    	  if(goods==null){
			   goods=new Goods();
			    session.setAttribute("goods",goods);
			}
		  
		  
           resp.setContentType("text/html;charset=GB2312");
		   
		   String action=req.getParameter("action");
		   
		   
//【】【】【】产品详细信息【】【】【】		  
		   if(action==null){return;}
	      else if(action.equals("goodsdetail")){
	    	 
		   String path="ProductShow_wupingjia.jsp";
		   Map goodsmsg = new HashMap();
		   String goodsId=req.getParameter("goodsid");
		   goods.setGoodsid(goodsId);
		   int goodsid=Integer.valueOf(goodsId);
		   if(goodsid!=0){
			  try{
				 int i=1;
				 System.out.println("前"+goods.getGoodsintroduction()); 
				 if(DAOFactory.getGoodsDAOinstance().selectgoods(goodsid)!=null){
				      goodsmsg=(Map) DAOFactory.getGoodsDAOinstance().selectgoods(goodsid);
				      
				// if(goodsmsg.get(1)!=null&goodsmsg.get(2)!=null){
				   while(goodsmsg.get(i++)!=null&i<8){
				      goods.setGoodsname((String)goodsmsg.get(1));
				      goods.setGoodstype((String)goodsmsg.get(2));
				      goods.setPrice((String)goodsmsg.get(3));
				      goods.setPhoto((String)goodsmsg.get(4));
				      goods.setChuxiao(Integer.valueOf((String)goodsmsg.get(5)));
				      goods.setPhotourl((String)goodsmsg.get(6));
					  goods.setGoodsmount(Integer.valueOf((String)goodsmsg.get(7)));
					  goods.setGoodsintroduction((String)goodsmsg.get(8));
					  System.out.println(goodsmsg.get(9));
				      goods.setGoodsdate((Date)goodsmsg.get(9)); 
				      
				  }
					
					System.out.println("后"+goods.getGoodsintroduction()); 
					
				} 
				 req.getRequestDispatcher(path).forward(req, resp);
			 }catch(Exception e){
				e.printStackTrace();
			 }
		   } 
		}
	    
// 【】【】【】【】 action=cart     【】【】【 【】   @leon   
	      
	      
	      else if(action.equals("cart")){
	    	 
	    	 
	    	  Cart cart=(Cart) session.getAttribute("cart");
	    	  if(session.getAttribute("uname")==null){
	    		  req.getRequestDispatcher("register.jsp").forward(req, resp);
	    	  }
	    	  else{
	    	  System.out.println("session.getAttributeuname"+session.getAttribute("uname"));
	    	  if(cart==null){
	    		   cart=new Cart();
	    		   System.out.println("session cart is new");
	    		   session.setAttribute("cart", cart);
	    	  }
	    	  
	    	  //System.out.println("goodsid"+goodsid);
	    	  int goodsid =Integer.parseInt((String)req.getParameter("goodsid"));//将前台获取的goodsid转型为int
	    	  cart.addcart((String)req.getParameter("goodsid"));     //讲goodsid添加到购物车，添加到购物车若是第一次，map value设置为1，有添加过的，map value+1
	    	  Map<String, Integer> carts = cart.getcart();           //获取购物车中的信息
	    	  Set<String> goodsids=carts.keySet();   //获取key值  即 goodsid
	    	  int goodscategogy=goodsids.size();
	    	    //System.out.println("goodscategogy"+goodscategogy);
	    	  Iterator<String> it=goodsids.iterator();
	    	 
	    	   List<String> namelist=new ArrayList<String>();
	    	   List<Float> pricelist=new ArrayList<Float>();
	    	   List<Integer> cuxiaolist=new ArrayList<Integer>();
	    	   List<Integer> shulianglist = new ArrayList<Integer>();
	    	   List<String> idlist=new ArrayList<String>();
	    	     // shulianglist=null;
	    	      int i=0;
	    	      float totalprice = 0 ;
	    	    while(it.hasNext()){
	    		   try {
	    			      String str=it.next();
						Map goodscart=(Map)DAOFactory.getGoodsDAOinstance().selectgoods(Integer.valueOf(str));					
						
						    cart.setGoodscartcount(goodscategogy); //设置购物车中产品的种类数量
						  //  System.out.println("carts.get(it.next())"+carts.get(goodsids.iterator().next()));
						    namelist.add(i,(String) goodscart.get(1));
						    pricelist.add(i,Float.parseFloat((String)goodscart.get(3)));
						    cuxiaolist.add(i,Integer.parseInt((String)goodscart.get(5)));
						    idlist.add(i,str);
						    System.out.println("[][][][[]][]");
						   // System.out.println("carts.get(it.next())"+carts.get(it.next()).toString());carts.get(Integer.valueOf((String)it.next()))
						   //String str=it.next();
						    if(Integer.valueOf(str)!=0){
						    System.out.println("carts.get(it.next())");
						    int goodsnum = carts.get(str);      //获取key对应的值 ，即数量；
						    
						    shulianglist.add(i,goodsnum);   //grherhrhwerhwerhwehewh
						    System.out.println("Float.parseFloat((String)goodscart.get(3))"+Float.parseFloat((String)goodscart.get(3))*goodsnum);
						    totalprice=totalprice+goodsnum*(Float.parseFloat((String)goodscart.get(3)));	
						    i++;
						  }						    
						   // System.out.println("carts.get(it.next())"+carts.get(goodsids.iterator().next()));
						} catch (Exception e) {				
							e.printStackTrace();    		   
	    	          }						
	    	    }
	    	   cart.setNamelist(namelist);
	    	   cart.setPricelist(pricelist);
	    	   cart.setCuxiaolist(cuxiaolist);
	    	   cart.setShulianglist(shulianglist);
	    	   cart.setTotalprice(totalprice);
	    	   cart.setIdlist(idlist);
	    	  
	    	   String path="cart.jsp";					      
		    	  req.getRequestDispatcher(path).forward(req, resp);
	    	}
	      }
		   
//【】【】【】【】 更改数量【】【】【】【】	   
	
	      else if(action.equals("genggai")){
	    	  String goodsid=req.getParameter("goodsid");
	    	  String goodsnum=req.getParameter("shuliang");
	    	  Cart cart=(Cart) session.getAttribute("cart");
	    	  if(cart==null){
	    		   cart=new Cart();
	    		   System.out.println("session cart is new");
	    		   session.setAttribute("cart", cart);
	    	  }
	    	  
	    	 System.out.println("goodsid"+goodsid);
	//    	  int goodsid =Integer.parseInt((String)req.getParameter("goodsid"));//将前台获取的goodsid转型为int
	    //	  cart.addcart((String)req.getParameter("goodsid"));     //讲goodsid添加到购物车，添加到购物车若是第一次，map value设置为1，有添加过的，map value+1
	    	  Map<String, Integer> carts = cart.getcart();  //获取购物车中的信息	    	 
	    	  Set<String> goodsids=carts.keySet();   //获取key值  即 goodsid	    	
	    	  Iterator<String> it=goodsids.iterator();	    	  
	    	  List<Integer> shulianglist = cart.getShulianglist();
	       	     int i=0;
	    	     float totalprice = 0 ;
	    	     while(it.hasNext()){
	    		   try {			    
	    			      String str=it.next();
	    			      System.out.println("str"+str);
	    			    
	    			      if(str.equals(goodsid)){        //str标识以前的goodsid 判断和现在要修改的goodsid相比较，如果相同。。。。不过不同。。。	    			    	  
	    			    	  shulianglist.set(i,Integer.parseInt(goodsnum));
	    			    	  System.out.println("shulianglist.get(i)"+shulianglist.get(i)+"【新获取的goodsid】"+goodsid+"【以前的goodsid的数量】"+carts.get(str));
	    			          System.out.println("【新的单价】"+cart.getPricelist().get(i));	    			      
	    			          System.out.println("carts.get(str)【前一次数量】"+carts.get(str)+"【后一次】"+Integer.parseInt(goodsnum)+"【前后数量差】"+(Integer.parseInt(goodsnum)-carts.get(str)));
	    			          totalprice=((Integer.parseInt(goodsnum)-carts.get(str))*cart.getPricelist().get(i)+cart.getTotalprice());					 						  		
							  carts.put(goodsid,Integer.parseInt(goodsnum)); //讲map中数量更换给最新输入的值
				    	      System.out.println("更换后carts.get(goodsid)"+carts.get(goodsid));									
	    			      }
	    			      i++;   
									
						} catch (Exception e) {				
							e.printStackTrace();    		   
	    	          }						
	    	    }
	    	  
	    	   cart.setShulianglist(shulianglist);
	    	   cart.setTotalprice(totalprice);
	    	
	    	   String path="cart.jsp";					      
		    	  req.getRequestDispatcher(path).forward(req, resp);
	    	}
		   	   
		   
		   /*    else if(action.equals("genggai")){
	    	  List<Integer> shulianglist = new ArrayList<Integer>();
	    	  List<String> idlist=new ArrayList<String>();
	    	  List<Float> pricelist=new ArrayList<Float>();
	    	  Cart cart=(Cart) session.getAttribute("cart");
	    	  float totalprice=0;
	    	  if(cart==null){
	    		   cart=new Cart();
	    		   System.out.println("session cart is new");
	    		   session.setAttribute("cart", cart);
	    	  }
	    	  Map<String, Integer> carts = cart.getcart(); 
	    	  String goodsid=req.getParameter("goodsid");
	    	  String goodsnum=req.getParameter("shuliang");
	    	  System.out.println("goodsid"+goodsid+"goodsnum"+goodsnum);
	    	  int categogy=cart.getGoodscartcount();//获取商品种类数，一次查找与获取到的goodsid相同的
	    	  for(int i=0;i<categogy;i++){
	    		  if(cart.getIdlist().get(i).equals(goodsid)){
	    			  System.out.println("现在的数量-原来的数量"+ cart.getShulianglist().get(i));
	    			  //System.out.println("现在的数量-原来的数量"+(Integer.parseInt(goodsnum)-cart.getShulianglist().get(i))+"  "+cart.getPricelist().get(i)+"  "+cart.getTotalprice());
	    			 //int oldgoodsnum=cart.getShulianglist().get(i);
	    			  totalprice=((Integer.parseInt(goodsnum)-cart.getShulianglist().get(i))*cart.getPricelist().get(i)+cart.getTotalprice());// 由于提交一次同时数量也增加了
	    			  System.out.println("totalprice"+totalprice);
	    			  shulianglist.add(Integer.parseInt(goodsnum));	    			  
	    		  }
	    		cart.setShulianglist(shulianglist);
	    		
	    	  }
	    	  
	    	  cart.setTotalprice(totalprice);
	    	  cart.setShulianglist(shulianglist);
	    	  String path="cart.jsp";					      
	    	  req.getRequestDispatcher(path).forward(req, resp);
	      }
		   
	*/ 	 
		 //【】【】【】【】 删除【】【】【】【】	 		   
	      else if(action.equals("shanchu")){
	    	 String goodsid=req.getParameter("goodsid");
	    	 Cart cart=(Cart) session.getAttribute("cart");
	    	  cart.deletecart(goodsid);
	    	  Map<String, Integer> carts = cart.getcart();           //获取购物车中的信息
	    	  
	    	  Set<String> goodsids=carts.keySet();   //获取key值  即 goodsid
	    	  int goodscategogy=goodsids.size();
	    	    //System.out.println("goodscategogy"+goodscategogy);
	    	  if(goodscategogy!=0){
	    	  Iterator<String> it=goodsids.iterator();
	    	 
	    	   List<String> namelist=new ArrayList<String>();
	    	   List<Float> pricelist=new ArrayList<Float>();
	    	   List<Integer> cuxiaolist=new ArrayList<Integer>();
	    	   List<Integer> shulianglist = new ArrayList<Integer>();
	    	   List<String> idlist=new ArrayList<String>();
	    	     // shulianglist=null;
	    	      int i=0;
	    	      float totalprice = 0 ;
	    	    while(it.hasNext()){
	    		   try {
	    			      String str=it.next();
						Map goodscart=(Map)DAOFactory.getGoodsDAOinstance().selectgoods(Integer.valueOf(str));					
						
						    cart.setGoodscartcount(goodscategogy); //设置购物车中产品的种类数量
						  //  System.out.println("carts.get(it.next())"+carts.get(goodsids.iterator().next()));
						    namelist.add(i,(String) goodscart.get(1));
						    pricelist.add(i,Float.parseFloat((String)goodscart.get(3)));
						    cuxiaolist.add(i,Integer.parseInt((String)goodscart.get(5)));
						    idlist.add(i,str);
						    System.out.println("[][][][[]][]");
						   // System.out.println("carts.get(it.next())"+carts.get(it.next()).toString());carts.get(Integer.valueOf((String)it.next()))
						   //String str=it.next();
						  if(Integer.valueOf(str)!=0){
						    System.out.println("carts.get(it.next())");
						    int goodsnum = carts.get(str);      //获取key对应的值 ，即数量；
						    
						    shulianglist.add(i,goodsnum);   //grherhrhwerhwerhwehewh
						    System.out.println("Float.parseFloat((String)goodscart.get(3))"+Float.parseFloat((String)goodscart.get(3))*goodsnum);
						    totalprice=totalprice+goodsnum*(Float.parseFloat((String)goodscart.get(3)));	
						    i++;
						  }						    
						   // System.out.println("carts.get(it.next())"+carts.get(goodsids.iterator().next()));
						} catch (Exception e) {				
							e.printStackTrace();    		   
	    	          }						
	    	      }//while
	    	         cart.setNamelist(namelist);
	    	         cart.setPricelist(pricelist);
	    	         cart.setCuxiaolist(cuxiaolist);
	    	         cart.setShulianglist(shulianglist);
	    	         cart.setTotalprice(totalprice);
	    	         String path="cart.jsp";					      
		    	     req.getRequestDispatcher(path).forward(req, resp);
	                  } //if
	    	            else{
	    		        float totalprice=0;
	    		        cart.setTotalprice(totalprice);
	    		        req.getRequestDispatcher("cartempty.jsp").forward(req, resp);
	    		   } 	    	 
	      }
	      else if(action.equals("selectBytype")){
	    	  List<String[]> goodsnum=new ArrayList<String[]>();   //goodsnum表示选择之后的产品种类数
	    	// String goodstype=(String)req.getParameter("goodstype");
	    	  String goodstype = new String(req.getParameter("goodstype").getBytes("ISO-8859-1"),"GB2312");
	    	  //String goodstype=new String(req.getParameter("goodstype")) ;
	    	  //String goodstype = new String(req.getParameter("goodstype").getBytes("UTF-8"));
	    	  System.out.println("goodstype类型" + goodstype);
	    	  try{
	    		  goodsnum=DAOFactory.getGoodsDAOinstance().selectgoodsByType(goodstype);
	    		  req.setAttribute("goodsnum", goodsnum);
	    		  req.getRequestDispatcher("SelectGoods.jsp").forward(req, resp);
	    	  }catch(Exception e){
	    		  e.printStackTrace();
	    	  }
	         }

		   //【】【】【】购买【】【】【【】   购买时产生订单，同时产生订单与商品ID的另一张表同时还发送邮件
	      else if(action.equals("buy")){
	    	  List<String[]> ordermsg;
	  //  	  MailSenderInfo mailInfo = new MailSenderInfo();
	    	  
	    	  String userid=(String) session.getAttribute("userid");
	    	  System.out.println("userid【】【】"+userid);
	    	  if(session.getAttribute("uname")==null){
	    		  req.getRequestDispatcher("register.jsp").forward(req, resp);
	    	  }
	    	  else{
	    		  //生成订单
	    		  Cart cart=(Cart)session.getAttribute("cart");
	    		
	    		  try {
	    			  int orderidreturn=DAOFactory.getOrderDAOinstance().createorder(cart, userid);
					if(orderidreturn!=1){
						System.out.println("【max】"+orderidreturn);
						
						ordermsg=DAOFactory.getOrderDAOinstance().selectorder(Integer.parseInt(userid));
						
						DAOFactory.getOrderDAOinstance().createorderdetail(cart, orderidreturn);//表示当生产订单的时候 同时也生成了订单详情，比如说媒个订单中有哪些产品。
						session.setAttribute("ordermsg",ordermsg);
						/*			String email=(String) session.getAttribute("email");
						System.out.println("email[][][][][]【】"+email);
						session.setAttribute("ordermsg",ordermsg);												 
						  mailInfo.setMailServerHost("smtp.163.com"); 
						  mailInfo.setMailServerPort("25"); 
						  mailInfo.setValidate(true); 
						  mailInfo.setUserName("liangzou1988@163.com"); 
						  mailInfo.setPassword("331571208");//您的邮箱密码 
						  mailInfo.setFromAddress("liangzou1988@163.com"); 
						  mailInfo.setToAddress(email); 
						  mailInfo.setSubject("欢迎您到本网站购物！"); 
						  mailInfo.setContent(session.getAttribute("realname")+"先生/女士您在本网站购买的商品购买成功,我们尽快给您配送，谢谢您的光顾。"); 
					        //这个类主要来发送邮件
						  System.out.println("][]["+mailInfo.getMailServerPort());
				
						  SimpleMailSender sms = new SimpleMailSender();
					         sms.sendTextMail(mailInfo);//发送文体格式 
					         sms.sendHtmlMail(mailInfo);//发送html格式
					         System.out.println("[][]send success!");              */
						req.setAttribute("Neworderid",orderidreturn );
						req.getRequestDispatcher("ZhiFuFangShi.jsp").forward(req, resp);}//createorder.jsp
					else{req.getRequestDispatcher("buy1.jsp").forward(req, resp);}
				
				} catch (Exception e) {					
					e.printStackTrace();
				}
	    	  }
	    	  
	      } 
   // 评价系统		   
	      else if(action.equals("pingjia")){
	    	  String pingjiainfo=req.getParameter("pingjiainfo");
	    	  String levelinfo=req.getParameter("RadioGroup1");	 
	    	  int goodsid=Integer.parseInt(req.getParameter("goodsid"));
	    	  int userid=Integer.parseInt((String)session.getAttribute("userid"));
	    	  System.out.println("【】"+pingjiainfo);
	    	 // int orderid=242;
	    	  try {
				if((DAOFactory.getPingJiaDAOinstance().insertinfo(pingjiainfo,levelinfo,userid, goodsid))!=0){
					  System.out.println("OK");
				  }
			    } catch (Exception e) {
				
				e.printStackTrace();
			}
			    req.getRequestDispatcher("pingjiasuccess.jsp").forward(req, resp); 
	      }
		   
	      else if(action.equals("chakanpingjia")){
	    	  List<String[]> pingjia=new ArrayList<String[]>();
	    	  int goodsid=Integer.parseInt(req.getParameter("goodsid"));
	    	 // String levelinfo=req.getParameter("pingjiainfo");	 
	    	 // int goodsid=Integer.parseInt(req.getParameter("goodsid"));
	    	  //int userid=Integer.parseInt((String)session.getAttribute("userid"));
	    	  System.out.println("【】");
	    	 // int orderid=242;
	    	  try {
	    		  pingjia=DAOFactory.getPingJiaDAOinstance().disply_pingjia(goodsid);
					  System.out.println("OK");
				    req.setAttribute("pingjia", pingjia);
			    } catch (Exception e) {
				
				e.printStackTrace();
			}
			    req.getRequestDispatcher("ProductShow_pingjia.jsp").forward(req, resp); 
	      }
		   
		   
	      else if(action.equals("Orderxiangqing")){
	    	  List<String[]> orderdetail=new ArrayList<String[]>();
	    	  int orderid=Integer.parseInt(req.getParameter("orderid"));
	    	  try {
	    		  orderdetail=DAOFactory.getOrderDAOinstance().selectorderdetail(orderid);
	    		  req.setAttribute("orderdetail", orderdetail);
	    		  System.out.println("[]");
			} catch (Exception e) {
				
				e.printStackTrace();
			}
	    	  req.getRequestDispatcher("Orderdetail.jsp").forward(req, resp);
	    	  
	      }
	      else if(action.equals("tousu")){
	    	  
	    	 int userid=Integer.parseInt((String) session.getAttribute("userid"));
	    	 int orderid=Integer.parseInt(req.getParameter("orderid"));
	    	 String tousuinfo=req.getParameter("textfield");
	    	 int tousuStyle=Integer.parseInt(req.getParameter("RadioGroup1"));
	    	 try {
				if(DAOFactory.getPingJiaDAOinstance().createTousu(tousuinfo, userid, orderid, tousuStyle)!=0){
					System.out.println("!!!!!!success!");
					 req.getRequestDispatcher("toususuccess.jsp").forward(req, resp);
				 }
			} catch (Exception e) {
				
				e.printStackTrace();
			}
	    	 	    	  
	      }//
		   
	      else if(action.equals("changeStatus")){
	    	  int userid=Integer.parseInt((String) session.getAttribute("userid"));
	    	  int orderid=Integer.parseInt(req.getParameter("orderid"));
	    	  Cart cart=(Cart)session.getAttribute("cart");
	    	  try{
	    		  DAOFactory.getOrderDAOinstance().updateBuyStatus(cart, orderid);
	    		  req.getRequestDispatcher("createorder.jsp").forward(req, resp);
	    	  }catch(Exception e){
	    		  e.printStackTrace();
	    	  }
	    	  
	      }
		 
	      else if(action.equals("KeFucaxun")){
	    	  List<String> selectKeFuTousuByCustmer=new ArrayList<String>();
			  int orderid=Integer.parseInt(req.getParameter("orderid"));
			  System.out.println("ggergege");
			  try{
				  selectKeFuTousuByCustmer=DAOFactory.getPingJiaDAOinstance().selectTousuByCustmer(orderid);
				  req.setAttribute("selectKeFuTousuByCustmer", selectKeFuTousuByCustmer);
				  req.getRequestDispatcher("tousuKeFu.jsp").forward(req, resp);
				  
			  }catch(Exception e)
			  { e.printStackTrace();}
		  }
	   
	}//在这个上面分界	   		   		   						    	   	     			
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
              this.doGet(req, resp);
		
	}

}
